package com.funever.receiver;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

public class AlarmReceiver extends BroadcastReceiver {
	
	public static final String ALARM_URI = "android.funever.alarm.uri";
	
	public static final String ALARM_FILE = "alarm.xml";
	
	PendingIntent sender;

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		 final AlarmManager am = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);
		if(arg1.getAction().equals(ALARM_URI)){
			NowAlarm na = NowAlarm.getInstance(arg0);
			if(na.canceled){
				return;
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(arg0);
			builder.setTitle("闹铃");
			builder.setMessage(na.message);
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//设置下一个闹铃
					if(sender!=null){
						am.cancel(sender);
					}
				}
			});
			builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//关闭铃声
					
				}
			});
			builder.show();
		}
	}
	
	 public void setAlarmTime(Context context,  long timeInMillis) {
	        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
	        Intent intent = new Intent(ALARM_URI);
	        intent.putExtra("time", timeInMillis);
	        sender = PendingIntent.getBroadcast(
	                context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        int interval = 60 * 1000 * 5;//闹铃间隔， 这里设为1分钟闹一次，在第2步我们将每隔1分钟收到一次广播
	        am.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, interval, sender);
	 }
	 
	 static class NowAlarm{
		 
		 long time;
		 
		 boolean canceled;
		 
		 String message;
		 
		 private static NowAlarm na;
		 
		 private NowAlarm(){
			 
		 }
		 
		 public static NowAlarm getInstance(Context ctx){
			 if(na==null){
				 na = new NowAlarm();
			 }
			 SharedPreferences preferences = ctx.getSharedPreferences(ALARM_FILE, Activity.MODE_PRIVATE);
			 na.time = preferences.getLong("time", 0);
			 na.canceled = preferences.getBoolean("canceled", false);
			 return na;
		 }
	 }

}
